//
//  YWDetail1TableViewController.m
//  百布业务
//
//  Created by 陈炳桦 on 15/11/4.
//  Copyright © 2015年 陈炳桦. All rights reserved.
//  我的发布 需求详情

#import "YWDetail1TableViewController.h"
#import "YWDetailHomeViewController.h"
#import "YWMyDemand.h"
#import <MBProgressHUD.h>
#import <UIImageView+WebCache.h>
#import "YWUpdateViewController.h"
#import "MLPhotoBrowserViewController.h"

@interface YWDetail1TableViewController () <MLPhotoBrowserViewControllerDataSource,MLPhotoBrowserViewControllerDelegate>

@property (nonatomic,strong) NSArray *conentArray;

// 提示符
@property (nonatomic,strong) MBProgressHUD *HUD;

@end

@implementation YWDetail1TableViewController

- (instancetype)init
{
    return [super initWithStyle:UITableViewStyleGrouped];
}

#pragma mark - 懒加载
- (NSArray *)conentArray{
    if (_conentArray == nil) {
        _conentArray = @[@"编号",@"类别",@"品种",@"数量",@"描述",@"手机",@"时间",@"需求类型",@"其他说明"];
    }
    return _conentArray;
}

- (MBProgressHUD *)HUD{
    if (_HUD == nil) {
        _HUD = [[MBProgressHUD alloc] initWithView:self.view];
        _HUD.mode = MBProgressHUDModeText;
        _HUD.margin = 20.f;
        [self.view addSubview:_HUD];
    }
    return _HUD;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
    
    // 设置底部菜单
    [self setUpButtomMenu];
}

- (void)setUpButtomMenu{
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];

    contentView.center = CGPointMake(BBScreenW - 50, BBScreenH - 160);
    [contentView setBackgroundColor:BBRGBColor(85, 26, 175)];
    [contentView.layer setCornerRadius:30.];
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_content_create"]];
    [icon setContentMode:UIViewContentModeScaleAspectFit];
    icon.frame = CGRectMake(0, 0, 30, 30);
    icon.center = CGPointMake(contentView.width * 0.5, contentView.width * 0.5);
    [contentView addSubview:icon];
    
    [contentView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonClick)]];
    
    [self.parentViewController.view addSubview:contentView];
}

- (void)buttonClick{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"修改需求" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        YWUpdateViewController *updateVC = [[YWUpdateViewController alloc] init];
        YWMyDemand *mydemand = ((YWDetailHomeViewController *)self.parentViewController).mydemand;
        updateVC.mydemand = mydemand;
        [self.navigationController pushViewController:updateVC animated:YES];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"删除需求" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self deleteDemand];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"关闭需求" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self closeDemand];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController:alert animated:YES completion:nil];

}

// 删除需求
- (void)deleteDemand{
    YWMyDemand *mydemand = ((YWDetailHomeViewController *)self.parentViewController).mydemand;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"buyerDemandId"] = mydemand.ID;
    param[@"status"] = @7;
    
    [YWNetwork updateStatusWithParameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {

        self.HUD.labelText = responseObject[@"msg"];
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];
        
        // 两秒后返回上一级
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.parentViewController.navigationController popViewControllerAnimated:YES];
        });
    
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        self.HUD.labelText = @"删除需求失败";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];
    }];
}

// 关闭需求
- (void)closeDemand{
    YWMyDemand *mydemand = ((YWDetailHomeViewController *)self.parentViewController).mydemand;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"buyerDemandId"] = mydemand.ID;
    param[@"status"] = @6;
    
    [YWNetwork updateStatusWithParameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        self.HUD.labelText = responseObject[@"msg"];
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];
        
        // 两秒后返回上一级
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.parentViewController.navigationController popViewControllerAnimated:YES];
        });
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        self.HUD.labelText = @"关闭需求失败";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];
    }];

}

#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    YWMyDemand *mydemand = ((YWDetailHomeViewController *)self.parentViewController).mydemand;
    if (mydemand.urls.count == 0) {
        return 10;
    }
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 8) {
        
        return 300;
    }
    
    return 44;
}

// headerview
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    YWMyDemand *mydemand = ((YWDetailHomeViewController *)self.parentViewController).mydemand;
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BBScreenW, 100)];
    
    CGFloat imageW = 80;
    CGFloat imageH = 80;
    CGFloat imageY = 10;
    CGFloat space = 10;     // 间距
    
    for (int i = 0; i < mydemand.urls.count; i++) {
        CGFloat imageX = i * (imageW + space) + space;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
        imageView.tag = i + 1;
        
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewClick:)]];
        
        NSURL *url = [NSURL URLWithString:mydemand.urls[i]];
        [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"default_no_img"]];
        [headerView addSubview:imageView];
    }
    
    return headerView;
}

- (void)imageViewClick:(UITapGestureRecognizer *)gesture{
//    NSLog(@"%@",gesture.view);
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:gesture.view.tag - 1 inSection:0];
    // 图片游览器
    MLPhotoBrowserViewController *photoBrowser = [[MLPhotoBrowserViewController alloc] init];
    // 淡入淡出效果
    photoBrowser.status = UIViewAnimationAnimationStatusFade;
    // 数据源/delegate
    photoBrowser.delegate = self;
    photoBrowser.dataSource = self;
    // 当前选中的值
    photoBrowser.currentIndexPath = [NSIndexPath indexPathForItem:indexPath.row inSection:0];
    // 展示控制器
    [photoBrowser show];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.conentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    // 取消选中状态
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.textLabel.text = self.conentArray[indexPath.row];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 31)];
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor grayColor];
    label.textAlignment = NSTextAlignmentRight;
    label.tag = indexPath.row;
    // 设置文字
    [self setText:label];

    cell.accessoryView = label;
    
    return cell;
}

- (void)setText:(UILabel *)label{
    
    YWMyDemand *mydemand = ((YWDetailHomeViewController *)self.parentViewController).mydemand;
    switch (label.tag) {
        case 0:     // 编号
            label.text = mydemand.ID;
            break;
        
        case 1: //类别
            if ([mydemand.sampleTypeId isEqualToString:@"1"])
                label.text = @"面料";
            else if ([mydemand.sampleTypeId isEqualToString:@"2"])
                label.text = @"辅料";
            break;
            
        case 2: // 品种
            label.text = mydemand.keyWord;
            break;
            
        case 3: // 数量
            label.text = mydemand.needCount;
            break;
            
        case 4: // 描述
            label.text = mydemand.sampleDescribe;
            break;
            
        case 5: // 手机
            label.text = mydemand.mobile;
            break;
            
        case 6: // 时间
            label.text = [self getTime:mydemand.createTimeFormat];
            break;
            
        case 7: // 需求类型
            label.text =  [self getType:mydemand.demandFrom];
            break;
            
        case 8: // 其他说明
            label.text = mydemand.demandMemo;
            [label sizeToFit];
            break;
        default:
            break;
    }
}

// 计算时间
- (NSString *)getTime:(NSString *)timeString{
    NSString *day = nil;
    NSString *time = nil;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date = [formatter dateFromString:timeString];
    
    formatter.dateFormat = @"MM-dd";
    day = [formatter stringFromDate:date];
    
    
    formatter.dateFormat = @"HH:mm";
    time = [formatter stringFromDate:date];
    
    return [NSString stringWithFormat:@"%@ %@",day,time];
}

// 获取需求类型
- (NSString *)getType:(NSString *)string{
    
    if ([string isEqualToString:@"7"]) {
        return @"需求";
    }else if([string isEqualToString:@"8"]){
        return @"下单";
    }else if([string isEqualToString:@"9"]){
        return @"集中采购";
    }
    
    return @"未知类型";
}

#pragma mark - <MLPhotoBrowserViewControllerDataSource>
- (NSInteger)photoBrowser:(MLPhotoBrowserViewController *)photoBrowser numberOfItemsInSection:(NSUInteger)section{
    YWMyDemand *mydemand = ((YWDetailHomeViewController *)self.parentViewController).mydemand;
    return mydemand.urls.count;
}

#pragma mark - 每个组展示什么图片,需要包装下MLPhotoBrowserPhoto
- (MLPhotoBrowserPhoto *) photoBrowser:(MLPhotoBrowserViewController *)browser photoAtIndexPath:(NSIndexPath *)indexPath{
    // 包装下imageObj 成 ZLPhotoPickerBrowserPhoto 传给数据源
    MLPhotoBrowserPhoto *photo = [[MLPhotoBrowserPhoto alloc] init];
    YWMyDemand *mydemand = ((YWDetailHomeViewController *)self.parentViewController).mydemand;
    photo.photoObj = [mydemand.urls objectAtIndex:indexPath.row];
    return photo;
}


@end
